package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验手机号和密码是否正确或者为空
        if (dto.getPhone().equals("")|| dto.getPassword().equals("")){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //2.查看该对象是否存在
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //3.检验密码
        String salt = apUser.getSalt();

        String md5Password = MD5Utils.encode(salt + dto.getPassword()); ;

        if (!md5Password.equals(apUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //4.返回token
        HashMap<String, Object> data = new HashMap<>();
        data.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));

        HashMap<String,Object> user = new HashMap<>();
        user.put("id",apUser.getId());

        return ResponseResult.okResult(data);
    }

    /**
     * cookie中存放token（jwt校验）
     * cookie中取出key 该key对应的value为redis中jwt的key
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto, HttpServletResponse response) {
        //1.校验手机号和密码是否正确或者为空
        if(ObjectUtils.isEmpty(dto))
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        if (dto.getPhone().equals("")|| dto.getPassword().equals("")){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //2.查看该对象是否存在
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //3.检验密码
        String salt = apUser.getSalt();
        String password = dto.getPassword();

        String md5Password = MD5Utils.encodeWithSalt(salt,password);
        if (!md5Password.equals(apUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //4.在redis中存放用户信息的值 并且将过期时间设置为2小时 key为token+userId value为userInfo
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(uuid, JSON.toJSONString(apUser),2, TimeUnit.HOURS);

        //cookie中取出key 该key对应的value为redis中jwt的key
        Cookie cookie = new Cookie("uuid",uuid);

        response.addCookie(cookie);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
